//
//  LoginViewController.m
//  soccer
//
//  Created by 上官千城 on 15/9/10.
//  Copyright (c) 2015年 上官千城. All rights reserved.
//

#import "LoginViewController.h"

@interface LoginViewController ()

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    //从数据库调取用户token
    [[Account shareHandle]createRegisterTable];
    //背景
    UIImageView *backView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
    backView.image = [UIImage imageNamed:@"注册详情页_02@2x"];
    [self.view addSubview:backView];
    //用户名
    self.userName = [[UITextField alloc]initWithFrame:CGRectMake(40, 150, WIDTH - 80, 30)];
    self.userName.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:self.userName];
    //密码
    self.password1 = [[UITextField alloc]initWithFrame:CGRectMake(self.userName.frame.origin.x, self.userName.frame.origin.y + self.userName.frame.size.height + 30, self.userName.frame.size.width, self.userName.frame.size.height)];
    self.password1.borderStyle = UITextBorderStyleRoundedRect;
    self.password1.textColor = [UIColor whiteColor];
    self.password1.secureTextEntry = YES;
    [self.view addSubview:self.password1];
    //登陆
    UIButton *login = [UIButton buttonWithType:UIButtonTypeCustom];
    [login addTarget:self action:@selector(loginAction) forControlEvents:UIControlEventTouchUpInside];
    login.frame = CGRectMake(self.password1.frame.origin.x + 20 , self.password1.frame.origin.y + self.password1.frame.size.height + 60, 120, 30);
    [login setTitle:@"登陆" forState:UIControlStateNormal];
    login.backgroundColor = [UIColor orangeColor];
    [self.view addSubview:login];
    //注册
    UIButton *Registered = [UIButton buttonWithType:UIButtonTypeCustom];
    Registered.frame = CGRectMake(login.frame.origin.x + login.frame.size.width +20, login.frame.origin.y, login.frame.size.width, login.frame.size.height);
    Registered.backgroundColor = [UIColor orangeColor];
    [Registered setTitle:@"注册" forState:UIControlStateNormal];
    [Registered addTarget:self action:@selector(registereAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:Registered];
//忘记密码
    UIButton *forget = [UIButton buttonWithType:UIButtonTypeCustom];
    forget.frame = CGRectMake(self.password1.frame.origin.x+self.password1.frame.size.width - 70, self.password1.frame.origin.y + self.password1.frame.size.height+5, 90, 20);
    [forget addTarget:self action:@selector(forgetButton) forControlEvents:UIControlEventTouchUpInside];
    [forget setTitle:@"忘记密码" forState:UIControlStateNormal];
    [self.view addSubview:forget];

}

//忘记密码
-(void)forgetButton
{
    
}

//登陆
-(void)loginAction
{
 
    //登陆地址
    NSString *str2 = [NSString stringWithFormat:@"http://192.168.1.222:9099/OServer/OLogin?account=%@&pwd=%@",self.userName.text,self.password1.text];
    
    
    //http://{ip}:{port}/OServer/OUserRegister?account={account}&pwd={pwd}&phone={phone}&productId={productId}
    

        //开始登陆
        NSDictionary *dic2;
        NSString *erc2 = [HTTP Login:str2 dataDictionary:&dic2];
        NSInteger ifErc2 = [erc2 integerValue];
        
        NSLog(@"dic2 ==%@  erc2 == %@",dic2,erc2);
        if (ifErc2 == 0 ) {
            NSLog(@"登陆成功");
            //将用户信息存入数据库
            Register *reg = [[Register alloc]init];
            reg.token = [dic2 objectForKey:@"token"];
            self.token = reg.token;
            NSLog(@"%@",self.token);
            reg.sign = [dic2 objectForKey:@"sign"];
            self.sign = reg.sign;
            [[Account shareHandle]insertRegister:reg];
            //进入APP地址
            NSString *str3 = [NSString stringWithFormat:@"http://192.168.1.222:9099/OServer/OEnterApp?token=%@&sign=%@",self.token,self.sign];
            
            //开始进入APP
            NSDictionary *dic3;
            NSString *erc3 = [HTTP enterAPP:str3 dataDictionary:&dic3];
            NSLog(@"str3 = %@",str3);
            NSInteger ifErc3 = [erc3 integerValue];
            
            
            
            if (ifErc3 == 0) {
                NSLog(@"进入APP");
                NSString *userId = [dic3 objectForKey:@"userId"];
                NSString *userName = [NSString stringWithFormat:@"o_%@",userId];
                NSLog(@"-------------userName == %@",userName);
          //   登陆环信
                [[EaseMob sharedInstance].chatManager asyncLoginWithUsername:userName password:self.password1.text completion:^(NSDictionary *loginInfo, EMError *error) {
                    
                    if ([userName isEqualToString:[loginInfo objectForKey:@"username"]]) {
                        
                        NSLog(@"环信登陆成功");
                    }
                    
                    
                } onQueue:nil];
                [self.loginDelegate setRootViewControllerLog];
                ConsultSegmentController *view = [[ConsultSegmentController alloc]init];
                [self presentViewController:view animated:YES completion:^{
                    self.view.window.rootViewController = view;
                    
                }];

            }
            //进入APP失败
            else{
                NSLog(@"进入APP失败");
            }
            
        }
        //登陆失败
        if (ifErc2 > 0 && ifErc2 < 1000) {
            NSLog(@"登陆失败,退出APP");
        }
        
  

    
    
    
    
    
    
    
    
    
    
    
    
    
    
//        [self creatLogin];
//    [self creatEnterAPP];
    
}
//注册
-(void)registereAction
{
    RegisteredController *view = [[RegisteredController alloc]init];
    view.myDelegate = self;
    [self presentViewController:view animated:YES completion:^{
    }];

}

//注册协议方法
-(void)setRootViewControllerReg
{
    [self.loginDelegate setRootViewControllerLog];
    ConsultViewController *view = [[ConsultViewController alloc]init];
    [self presentViewController:view animated:YES completion:^{
        self.view.window.rootViewController = view;
        
    }];
    
   
}
//进入APP
-(void)creatEnterAPP
{
    //请求地址
    NSString *str = [NSString stringWithFormat:@"http://192.168.1.222:9099/OServer/OEnterApp?token=%@&sign=%@",self.userName.text,self.password1.text];
    //http://{ip}:{port}/OServer/OLogin?account={account}&pwd={pwd}
    
    NSURL *url = [NSURL URLWithString:str];
    
    //请求
    NSMutableURLRequest *requset1 = [NSMutableURLRequest requestWithURL:url];
    
    //响应
    NSURLResponse *response = [[NSURLResponse alloc]init];
    
    //服务器响应头文件
    NSData *data =  [NSURLConnection sendSynchronousRequest:requset1 returningResponse:&response error:nil];
    
    //转换中文
    NSString *str2 = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    
    NSLog(@"%@",str2);
    NSLog(@"%@",response);
    //http cookie 存储共享
    NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    
    //创建字典,存储 处理后头信息
    self.dic = [NSMutableDictionary dictionary];
    for (NSHTTPCookie *cookie in [cookieJar cookies]) {
        NSLog(@"%@", cookie.properties);
        for (NSString *key  in cookie.properties) {
            if ([key isEqualToString:@"Value"]) {
                self.name = [cookie.properties objectForKeyedSubscript:@"Value"];
            }
            if ([key isEqualToString:@"Name"]) {
                NSString *path = [cookie.properties objectForKeyedSubscript:@"Name"];
                NSString *str = [NSString stringWithFormat:@"%@=%@",path,self.name];
                //拼接后存到 字典
                [self.dic setValue:str forKey:@"Cookie"];
            }
        }
        
    }
    
    
    NSLog(@"dic = %@ ",self.dic);
    

}

-(void)creatLogin
{
    //请求地址
    NSString *str = [NSString stringWithFormat:@"http://192.168.1.222:9099/OServer/OLogin?account=%@&pwd=%@",self.userName.text,self.password1.text];
    //http://{ip}:{port}/OServer/OLogin?account={account}&pwd={pwd}
    NSURL *url = [NSURL URLWithString:str];
    
    //请求
    NSMutableURLRequest *requset1 = [NSMutableURLRequest requestWithURL:url];
    
    //响应
    NSURLResponse *response = [[NSURLResponse alloc]init];
    //服务器响应头文件
    NSData *data =  [NSURLConnection sendSynchronousRequest:requset1 returningResponse:&response error:nil];
    
    //转换中文
    NSString *str2 = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"%@",str2);
    NSLog(@"%@",response);
    
    //http cookie 存储共享
    NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    
    //创建字典,存储 处理后头信息
    self.dic = [NSMutableDictionary dictionary];
    
    for (NSHTTPCookie *cookie in [cookieJar cookies]) {
        NSLog(@"%@", cookie.properties);
        for (NSString *key  in cookie.properties) {
            if ([key isEqualToString:@"Value"]) {
                self.name = [cookie.properties objectForKeyedSubscript:@"Value"];
            }
            if ([key isEqualToString:@"Name"]) {
                NSString *path = [cookie.properties objectForKeyedSubscript:@"Name"];
                NSString *str = [NSString stringWithFormat:@"%@=%@",path,self.name];
                //拼接后存到 字典
                [self.dic setValue:str forKey:@"Cookie"];
            }
        }
        
    }
    
    
    NSLog(@"dic = %@ ",self.dic);
    

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
